﻿using CodeApi.Context;
using CodeApi.Models;
using CodeApi.tool;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CodeApi.Controllers
{
    [Route("api/[controller]/[action]")]
    public class UserController : ControllerBase
    {


        public UserContext userContext { get; set; }
        public readonly IAuthenticateService authenticate;
        public UserController(UserContext userContext, IAuthenticateService service)
        {
            this.userContext = userContext;
            this.authenticate = service;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<UserModel>> getUserMessage(int id)
        {
            var articleModel = await userContext.userTable.FindAsync(id);
            return articleModel;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userModel"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult> Login([FromBody] LoginRequestDTO userModel)
        {
            if (await userContext.userTable.AnyAsync(t=>t.u_email==userModel.Email) && await userContext.userTable.AnyAsync(t => t.u_password == userModel.Password))
            {
                String Token = "";
                if (authenticate.IsAuthenticated(userModel,out Token))
                {
                    return new ObjectResult(new { UserModel = userContext.userTable.Where(t => t.u_email == userModel.Email && t.u_password == userModel.Password) ,Token=Token});
                }else
                    return BadRequest("Invalid Request");
            }
            else
            {
                return BadRequest("Invalid Request");
            }
        }

    }
}
